﻿var grid = null;

$(function () {
    $("#txtStartDate,#txtEndDate").ligerDateEditor({
        showTime: false,
        format: "yyyy-MM-dd",
        width: 100,
        cancelable: false
    });

    $("#departmentCode").ligerComboBox({
        width: 100,
        cancelable: false,
        url: "/Scheduling/SchedulingList/GetDepartmentList?ram" + Math.random(),
        valueField: "value",
        textField: "text",
        valueFieldID: 'hdnDepartmentCode',
        onSuccess: function (data) {
            $("#departmentCode").ligerComboBox().setValue($("#hdnCurrDepCode").val());
        }
    });

    $("#btnSearch").click(function () {
        search();
    });
    $("#btnExport").click(function () {
        exportReport();
    });
    $("#btnPrint").click(function () {
        print();
    });
    $("#btnPrintView").click(function () {
        printView();
    });
    $('#btnSearch').click();
});


//显示排班
function search(pageNumber) {
    var queryData = {
        startDate: $("#txtStartDate").val(),
        endDate: $("#txtEndDate").val(),
        departmentCode: $("#hdnDepartmentCode").val()
    };
    var columns = getColumns();
    initTable(queryData, columns);
}

//加载列表
function initTable(queryData, columns) {
    grid = $("#maingrid").ligerGrid({
        height: '100%',
        url: '/Scheduling/SchedulingList/Search?ram=' + Math.random(),
        parms: queryData,
        pageSize: 30,
        heightDiff: 5,
        usePager: false,
        rownumbers: false,
        enabledSort: false,
        rowDraggable: false,
        enabledEdit: false,
        columns: columns,
        onAfterShowData: grid != null ? null : function (data) {
            if (JSON.stringify(data).indexOf("font") != -1) {
                return;
            }

            var dataCount = 0;
            for (var i = 0; i < grid.columns.length; i++) {
                if (grid.columns[i].name.toString().indexOf("D_") != -1) {
                    dataCount++;
                }
            }

            var otherCount = grid.columns.length - dataCount - 1; //1是排班日期后的列数
            var index = otherCount * grid.getData().length;

            for (var i = 0; i < grid.getData().length; i++) {
                for (var ii = otherCount; ii < grid.columns.length; ii++) {
                    var columnName = grid.columns[ii].name.toString();
                    if (columnName.indexOf("D_") != -1) {
                        var cell = $($(".l-grid-row-cell-inner")[index]);
                        var cellVal = grid.rows[i][grid.columns[ii].name.toString()];
                        if (cellVal != null && cellVal != "") {
                            cell.html('');
                            var cellValList = cellVal.split(',');
                            var idList = cellValList[0].split('|');
                            var codeList = cellValList[1].split('|');
                            var colorList = cellValList[2].split('|');
                            var newCellValue = "";
                            for (var iii = 0; iii < idList.length; iii++) {
                                newCellValue += "<font style=\"margin-left:4px; color:" + colorList[iii] + "\" categoryId=\"" + idList[iii] + "\">" + codeList[iii] + "</font>";
                            }
                            grid.updateCell(cell.parent()[0], newCellValue);
                        }
                    }
                    index++;
                }
            }
        }
    });
    GridNoData($("#maingrid"));
}

//获取表头
function getColumns() {
    var columns =
        [
            { display: '姓名', name: 'PersonnelName', width: 70, frozen: true },
            { display: '岗责', name: 'Remark', width: 90, frozen: true }
        ];

    $.ajax({
        url: "/Scheduling/Scheduling/GetDateTitle",
        data: { startDate: $("#txtStartDate").val(), endDate: $("#txtEndDate").val() },
        async: false,
        contentType: 'application/json;charset=utf-8',
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                for (var i = 0; i < d.Body.length; i++) {
                    var item = d.Body[i];
                    columns.push({ display: item.Date, columns: [{ display: (item.DayOfWeek == "六" || item.DayOfWeek == "日") ? ("<span style='color:red;'>" + item.DayOfWeek + "</span>") : item.DayOfWeek, name: item.DateId, width: 90, align: 'left' }] });
                }
            }
            else if (d.Result == 0) {
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });
    columns.push({ display: '总积休(小时)', name: 'SuperWorkHours', width: 100, editor: { type: 'float' }, render: function (row) { if (row.SuperWorkHours == 0) { return ''; } else { return row.SuperWorkHours } } });

    return columns;
}

Install_InsertReport();
var Installed = Install_Detect();
if (Installed) {
    CreateReport("Report");
    Report.LoadFromURL($("#hdnGrfUrl").val());
}

//导出报表
function exportReport() {
    var flag = checkDateRange();
    if (flag) {
        try {
            Report.OnExportBegin = OnExportBegin;
            Report.LoadDataFromURL("/Scheduling/Scheduling/GetSchedulingPrint?startDate=" + $("#txtStartDate").val() + "&endDate=" + $("#txtEndDate").val() + "&departmentCode=" + $("#hdnDepartmentCode").val() + "&type=1");
            Report.ExportDirect(1, "report.xls", true, true);
        }
        catch (e) {
            $('html,body').animate({ scrollTop: $(document).height() }, 1000);
        }
    }
}

//打印预览
function printView() {
    var flag = checkDateRange();
    if (flag) {
        location.href = "/Scheduling/Scheduling/PrintView?startDate=" + $("#txtStartDate").val() + "&endDate=" + $("#txtEndDate").val() + "&departmentCode=" + $("#hdnDepartmentCode").val() + "&type=1";
    }
}

//打印排班
function print() {
    var flag = checkDateRange();
    if (flag) {
        try {
            Report.LoadDataFromURL("/Scheduling/Scheduling/GetSchedulingPrint?startDate=" + $("#txtStartDate").val() + "&endDate=" + $("#txtEndDate").val() + "&departmentCode=" + $("#hdnDepartmentCode").val() + "&type=1");
            Report.Print(true);
        }
        catch (e) {
            $('html,body').animate({ scrollTop: $(document).height() }, 1000);
        }
    }
}

//设置导出参数
function OnExportBegin(OptionObject) {
    if (OptionObject.ExportType == 1) {
        var E2XLSOption = OptionObject.AsE2XLSOption;
        E2XLSOption.SameAsPrint = true;
        E2XLSOption.ExportPageBreak = true;
        E2XLSOption.ExportPageHeaderFooter = true;
        E2XLSOption.ColumnAsDetailGrid = true;
    }
}

//校验日期范围
function checkDateRange() {
    var flag = true;
    try
    {
        var tStartDate = new Date($("#txtStartDate").val().replace(/-/g,"/")).getTime();
        var tEndDate = new Date($("#txtEndDate").val().replace(/-/g, "/")).getTime();
        var day = ((tEndDate - tStartDate) / 1000 / (24 * 60 * 60)) + 1;
        if (day % 7 != 0) {
            $.ligerDialog.error("请选择日期范围为7天或者7天的倍数");
            flag = false;
        }
    }
    catch (ex) {
        $.ligerDialog.error("日期格式不正确");
        flag = false;
    }
    return flag;
}